package Components.Service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import Components.DAO.common.iface.DBProxyInterface;
import Components.DB.Buser;
import Components.Service.iface.ServiceProxyInterface;
import Loggers.MyLogger;

@Service
public class UserMessageCenterService {

	@Autowired
	DBProxyInterface dbProxyInterface;

	@Autowired
	ServiceProxyInterface commonService;

	/**
	 * check if the user existing.if so,just return a false signal.otherwise do
	 * the inserting operation and return a true signal.
	 * 
	 * @param username
	 * @param password
	 * @param remoteHost
	 * @return boolean
	 */
	public boolean UserRegisterSave(String username, String password,
			String remoteHost) {
		commonService.serviceMethos();
		// check if username exists
		Buser buser = null;
		try {
			buser = queryUserFromName(username);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		if (buser != null) {
			MyLogger.log(remoteHost + " register fail: username(" + username
					+ ") exists");
			return false;
		}

		// add the new user
		buser = new Buser();
		buser.setUsername(username);
		buser.setPassword(password);
		buser.setGeneral_ip(remoteHost);
		try {
			this.dbProxyInterface.save(buser);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * return an user objet if existing according to the input parameters.<br/>
	 * 
	 * @param username
	 * @return Buser
	 * @throws Exception
	 */
	public Buser queryUserFromName(String username) throws Exception {
		Buser buser = null;
		String hqlString = ("from Buser t where t.username=? and t.valid=1 ");
		List<Object> list = this.dbProxyInterface.query(hqlString,
				new String[] { username });
		if (!(list.isEmpty() || list.size() > 1)) {
			buser = (Buser) list.get(0);
		}
		return buser;
	}

}
